package com.thunbu.lib_common.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import java.util.*


/**
 *Created by Chaolue.Fan on 2021/5/13
描述:
 */
class ActivityManager private constructor() : Application.ActivityLifecycleCallbacks {

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ActivityManager()
        }
    }

    /**
     * 链表
     * 此处可以考虑 stack
     */
    private val activityList = LinkedList<Activity>()

    fun finishAllBefore() {
        try {
            val topActivity = getTopActivity()
            for (i in activityList.indices.reversed()) {
                val activity1 = activityList[i]
                if (activity1.hashCode() == topActivity.hashCode()) {
                    continue
                }
                activity1.finish()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 获取栈顶activity
     */
    fun getTopActivity(): Activity? {
        return if (activityList.isNotEmpty()) {
            activityList.last
        } else
            null
    }

    fun findActivity(clazz: Class<out Activity>): Activity? {
        activityList.forEach {
            if (it.javaClass == clazz) {
                return it
            }
        }
        Log.d("ActivityManager", "findActivity 里面没找到")
        return null
    }


    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        activityList.add(activity)
    }

    override fun onActivityStarted(activity: Activity) {

    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    override fun onActivityDestroyed(activity: Activity) {
        activityList.remove(activity)
    }
}